package com.gzr.demo01.unsafe.synchronized1;

// 不安全的买票
// 线程不安全
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"小黑").start();
        new Thread(station,"大白").start();
        new Thread(station,"牛子弟").start();
    }
}

// 买票
class BuyTicket implements Runnable{

    // 票
    private int ticketNums = 10;
    // 外部停止方式
    boolean flag = true;
    @Override
    public void run() {
        // 买票
        while (flag){
            buy();
        }
    }

    private synchronized void buy(){
        // 判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }
        // 模拟延时器
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}

